<?php

namespace app\models;

use app\components\BaseActiveRecord;
use Yii;
use yii\base\Exception;
use yii\helpers\Console;
use yii\helpers\FileHelper;

/**
 * This is the model class for table "{{%group}}".
 *
 * @property string $group_num
 * @property int $group_type
 * @property int $group_priority
 * @property int $create_time
 */
class Group extends BaseActiveRecord {

    public $defaultOrder = ['group_num' => SORT_DESC];
    public $sortAttributes = ['group_num'];
    public $primaryKey = 'group_num';


    /**
     * {@inheritdoc}
     */
    public static function tableName() {
        return '{{%group}}';
    }

    /**
     * {@inheritdoc}
     */
    public function rules() {
        return [
            [['group_num'], 'required'],
            [['group_type', 'group_priority', 'create_time'], 'integer'],
            [['group_num'], 'string', 'max' => 11],
            [['group_num'], 'unique'],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels() {
        return [
            'group_num' => '组号',
            'group_type' => '组类型',
            'group_priority' => '组优先级',
            'create_time' => '创建时间',
        ];
    }

    public function afterSave($insert, $changedAttributes) {
        parent::afterSave($insert, $changedAttributes);
        if ($this->isGenerateFile) {
            self::generateFiles($this);
        }
    }

    public static function generateFiles(Group $group) {
        $template = "GROUP:{$group->group_num}|||{$group->group_type}||{$group->group_priority}||0|END\n";
        $members = GroupUser::find()->where(['group_num' => $group->group_num])->asArray()->all();
        foreach ($members as $member) {
            $template .= "MEMBER:{$member['phone']}|{$member['group_priority']}|{$member['role']}|||||END\n";
        }

        $file = FILE_ROOT . "/{$group->group_num}.group";
        @file_put_contents($file, $template);
    }

    /**
     * @param $file
     * @throws \yii\db\Exception
     */
    public static function parseFile($file) {
        $string = file_get_contents($file);
        if (empty($string) || strpos($string, 'GROUP') === false) {
            Console::stdout("{$file} 解析失败.\n");
            return;
        }
        self::parseString($string);
    }

    /**
     * @param $string
     * @throws \yii\db\Exception
     */
    public static function parseString($string) {
        if (strpos($string, 'GROUP') === false) {
            return;
        }

        $model = null;
        $lines = explode("\n", $string);
        $line = str_replace('GROUP:', '', $lines[0]);
        $data = explode('|', $line);

        $group_num = $data[0];
        $model = Group::findOne(['group_num' => $group_num]);
        if (!$model) {
            $model = new Group();
        }
        $model->isGenerateFile = false;

        foreach ($lines as $line) {
            $model->parseGroup($line);
            $model->parseMember($line, $group_num);
        }

    }

    /**
     * @param $line
     * @throws \yii\db\Exception
     */
    protected function parseGroup($line) {
        if (strpos($line, 'GROUP') === false) {
            return;
        }
        $line = str_replace('GROUP:', '', $line);
        $data = explode('|', $line);
        $this->group_num = $data[0];
        $this->group_type = intval($data[3]);
        $this->group_priority = $data[5] ? intval($data[5]) : 1;
        $this->save();
    }

    /**
     * @param $line
     * @param $group_num
     * @throws \yii\db\Exception
     */
    protected function parseMember($line, $group_num) {
        if (strpos($line, 'MEMBER') === false) {
            return;
        }
        $line = str_replace('MEMBER:', '', $line);
        $data = explode('|', $line);
        $phone = $data[0];
        $model = GroupUser::findOne(['phone' => $phone, 'group_num' => $group_num]);
        if (!$model) {
            $model = new GroupUser();
        }
        $model->isGenerateFile = false;

        $model->group_num = $group_num;
        $model->phone = $phone;
        $model->group_priority = intval($data[1]);
        $model->role = intval($data[2]);
        $model->save(false);
    }
}
